package com.lenovo.baidu.post;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.lenovo.baidu.http.HttpMethod;
import com.lenovo.baidu.http.HttpTool;
import com.lenovo.baidu.http.TaskHome;

/**   
 *    
 * 项目名称：crawler   
 * 类名称：FocusPost   
 * 类描述：   首先 添加关注操作
 * 创建人：xinghf1   
 * 创建时间：2014年3月19日 上午11:29:17   
 * 修改人：xinghf1   
 * 修改时间：2014年3月19日 上午11:29:17   
 * 修改备注：   
 * @version    
 *    
 */
public class FocusPost {
	
	
	/**
	 * 
	 * @param tiebaName 根据给定的吧名签到
	 * @return 签到信息
	 */
	public  String signOneTieba(HttpContext localContext,CloseableHttpClient httpclient,CookieStore cookieStore, HttpMethod hm,String tiebaName)
	{
		HttpResponse response=null ;
		String url=null;
		String errinfo=null;
		String result=null;
		try {
			 HttpHost proxy = new HttpHost("10.4.10.190",8080,"http");
			 RequestConfig config = RequestConfig.custom()
	                    .setProxy(proxy)
	                    .build();
			url = "http://tieba.baidu.com/f?ie=utf-8&kw="+URLEncoder.encode(tiebaName,"utf-8");
			HttpGet gte_target=new HttpGet(url);
			gte_target.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; "
					+ "Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; "
					+ "Media Center PC 6.0)");
//			gte_target.addHeader("Accept","application/json, text/javascript, */*; q=0.01"
//					+ "image/gif, image/pjpeg, application/x-ms-xbap, */*");
//			gte_target.addHeader("Accept-Language","zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");//
//			gte_target.addHeader("Host","tieba.baidu.com");
//			gte_target.addHeader("Connection","Keep-Alive"); //
//			//gte_target.addHeader("Content-Length","143");
//			gte_target.addHeader("X-Requested-With","XMLHttpRequest");//
//		    gte_target.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			gte_target.addHeader("Cookie",HttpTool.cookiesToString(cookieStore));
//			gte_target.addHeader("Referer","http://tieba.baidu.com/f?ie=utf-8&kw=%E7%AC%94%E8%AE%B0%E6%9C%AC");//
			
			
	
				
				
			
			
				

			
			//进入指定贴吧
		
			 gte_target.setConfig(config);
			response=httpclient.execute(gte_target,localContext);
			 HttpEntity entity=response.getEntity() ;
			
			String[] paraTid=this.postPara(entity,cookieStore).split(":") ;
			 System.out.println(paraTid[0]+"======关键参数===========") ;  
			
//			 System.out.println("值2："+entity); 
//              String   content = EntityUtils.toString(entity); 
//            
//              String uid=TaskHome.getUID(content) ;
//            System.out.println(uid+"=================") ;  
			 
			
			
              
			String mapData="ie=utf-8&fname="+URLEncoder.encode(tiebaName,"utf-8")+"&tbs="+paraTid[0]+"&fid=52"+"&uid="+URLEncoder.encode("15010919094", "gbk");
		System.out.println(mapData+"======"); 
		
		
			url="http://tieba.baidu.com/f/like/commit/add";
//			HttpUriRequest login = RequestBuilder.post()
//                    .setUri(new URI(url))
//                    .addParameter("fname", tiebaName)
//                    .addParameter("ie", "gbk")
//                    .addParameter("tbs", paraTid[0])
//                    .addParameter("fid", "52")
//                    .addParameter("uid", "%B4%F3%D0%CB%B0%B2%C1%EB%CA%A8%D7%D3")
//                    .addHeader("Cookie",HttpTool.cookiesToString(cookieStore))
//                    .addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; "
//					+ "Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; "
//					+ "Media Center PC 6.0)")
//					.addHeader("Accept","application/json, text/javascript, */*; q=0.01"
//					+ "image/gif, image/pjpeg, application/x-ms-xbap, */*")
//                     .addHeader("Accept-Language","zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
//                     .addHeader("Host","tieba.baidu.com")
//                      .addHeader("Connection","Keep-Alive")
//                      .addHeader("Referer","http://tieba.baidu.com/f?ie=utf-8&kw=%E7%AC%94%E8%AE%B0%E6%9C%AC")
//                    .setConfig(config) 
//                    .build();
//	
//			 CloseableHttpResponse response2 = httpclient.execute(login);
//	            try {
//	           
//
//	                System.out.println("Login form get: " + response2.getStatusLine());
//	                EntityUtils.consume(entity);
//	                String loginInfo = HttpTool.htmlToString(response2.getEntity());
//                    System.out.println("最终返回值："+loginInfo);
//	                System.out.println("Post logon cookies:");
//	                List<Cookie> cookies = cookieStore.getCookies();
//	                if (cookies.isEmpty()) {
//	                    System.out.println("None");
//	                } else {
//	                    for (int i = 0; i < cookies.size(); i++) {
//	                        System.out.println("- " + cookies.get(i).toString());
//	                    }
//	                }
//	            } finally {
//	                
//	            }
		HttpURLConnection hcon=hm.sendPostRequest(url, mapData, HttpTool.cookiesToString(cookieStore), null);
			BufferedReader br=new BufferedReader(new InputStreamReader(hcon.getInputStream()));
			String line=null;
			StringBuffer sb=new StringBuffer();
			while((line=br.readLine())!=null)
			{
				sb.append(line);
			}
			//获取签到结果
			line=sb.toString();
			System.out.println("==获取签到结果="+line);
			line=HttpTool.mid(line, "\"no\":", ",");
			errinfo=HttpTool.mid(sb.toString(), "error\":\"", "\",");
			if(line.equals("0"))
			{
				result="在"+URLDecoder.decode(tiebaName, "gbk")+"吧签到成功";
				System.out.println(result);
			}
			else
			{
				errinfo=HttpTool.convert(errinfo);
				result="在"+URLDecoder.decode(tiebaName, "gbk")+"吧签到失败("+errinfo+")";
			System.out.println(result);
			}
			hcon.disconnect();
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return result;
	}
	
	public  String postPara(HttpEntity response,CookieStore cookieStore){
		String para="" ;
		try{
			String result=TaskHome.content("笔记本",cookieStore) ;
		//	String result=HttpTool.htmlToString(response);
			//拿到tbs
			String tbs=HttpTool.mid(result, "'is_login':1,\'tbs\':\'", "\'})");
//			String tbs=HttpTool.mid(HttpTool.htmlToString
//					(response), "'is_login':1,\'tbs\':\'", "\'})");
		//	String fid=HttpTool.mid(result,  "\"reply_num\":12,\"fid\":", ",\"fname\"");
			para=tbs+":"+"11" ;
			}catch(Exception ex){
				ex.printStackTrace();
			}
		return para ;
	}

	static public void main(String[] args){
	//	String content=TaskHome.content("笔记本") ;
		String tag=new FocusPost().postPara(null,null) ;
		System.out.println(tag);
	}
	
}
